package com.wangzz.mallchat.common.common.interceptor;

import cn.hutool.http.ContentType;
import com.wangzz.mallchat.common.common.domain.enums.HttpErrorEnum;
import com.wangzz.mallchat.common.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Optional;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    public static final String HEADER_AUTHORIZATION = "Authorization";
    public static final String UID = "uid";
    public static final String AUTHORIZARTION_SCHEMA = "Bearer ";

    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取token
        String token = getToken(request);
        Long uid = loginService.getValidUid(token);
        // 3.判断uid是否存在
        if (Objects.nonNull(uid)) {
            // 3.1 uid 存在，将uid添加附件
            request.setAttribute(UID, uid);
        } else {
            // 3.2 uid 不存在
            // 3.2.1 判断访问路径是否需要登录
            boolean isPublicUrl = isPublicUrl(request);
            if (!isPublicUrl) {
                // 3.2.2 需要登录（不是public）
                // 封装异常信息返回401
//                response.setStatus(401);
//                response.setContentType(ContentType.JSON.toString(StandardCharsets.UTF_8));
//                // 返回具体对象
//                response.getWriter().write("");
                HttpErrorEnum.UNAUTHORIZED.errorResponse(response);
                return false;
            }
        }
        // 3.3 放行
        return true;
    }

    private static boolean isPublicUrl(HttpServletRequest request) {
        String url = request.getRequestURI();
        String[] split = url.split("/");
        boolean isPublicUrl = split.length > 3 && "public".equals(split[3]);
        return isPublicUrl;
    }

    private static String getToken(HttpServletRequest request) {
        String header = request.getHeader(HEADER_AUTHORIZATION);
        // 2.解析token，获取uid
        String token = Optional.ofNullable(header)
                .filter(h -> h.startsWith(AUTHORIZARTION_SCHEMA))
                .map(value -> value.replace(AUTHORIZARTION_SCHEMA, ""))
                .orElse(null);
        return token;
    }
}
